from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from django.views.generic import list_detail, create_update
from readers.models import *
from readers.forms import UserProfileForm

def reader_plus(request):
	'''something like Google+'''
	return render_to_response('readers/reader_plus.html', {})

def reader_info(request, user_id):
	'''
	Show user/reader's basic info. and profile
	'''
	user = get_object_or_404(User, pk=user_id)

	try:
		reader = user.userprofile
		reading_books = Reading.objects.filter(status='C', user_reading=reader)
		reserving_books = Reserving.objects.filter(status='C', user_reserving=reader)
		ex_context = {
			'reader': reader,
			'reading_books': reading_books,
			'reserving_books': reserving_books
		}
	except UserProfile.DoesNotExist:
		ex_context = {
			'reader': None
		}

	return list_detail.object_detail(request,
		queryset = User.objects.all(),
		object_id = user_id,
		extra_context = ex_context,
		template_name = 'readers/reader_info.html',
		template_object_name = 'current_user')

@login_required
def reader_edit(request, user_id):
	'''CRUD reader info.'''
	action = request.GET.get('a', 'r')
	user = get_object_or_404(User, id=user_id)

	if action == 'c':
		return create_update.create_object(request,
			form_class = UserProfileForm,
			template_name = 'readers/reader_edit.html',
			post_save_redirect = '/readers/%s/' % user_id,
			extra_context = { 'action': action },
			login_required = True)
	elif action == 'u':
		return create_update.update_object(request,
			form_class = UserProfileForm,
			object_id = user.userprofile.id,
			template_name = 'readers/reader_edit.html',
			template_object_name = 'update_reader',
			post_save_redirect = '/readers/%s/' % user_id,
			extra_context = { 'action': action },
			login_required = True)
	elif action == 'd':
		return create_update.delete_object(request,
			model = UserProfile,
			object_id = user.userprofile.id,
			template_name = 'readers/reader_edit.html',
			template_object_name = 'delete_reader',
			post_delete_redirect = '/readers/%s/' % user_id,
			extra_context = { 'action': action },
			login_required = True)
	else:
		action = 'r'
		return HttpResponseRedirect('/readers/%s/' % user_id) # user_id is unicode
